<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
    /**
     *  vb    function其都可以拷贝
     * 可以实际实用
     *  Number,String,Boolean,Null,Undefined,多层Object,
     *  多层Array,function,RegExp都可以拷贝
     */
    const deepClone = function(obj) {
        // 先检测是不是数组和Object
        let isArr =Object.prototype.toString.call(obj) === '[object Array]';
        let isJson = Object.prototype.toString.call(obj) === '[object Object]';
        if (isArr) {
            // 克隆数组
            let newObj = [];
            for (let i = 0; i < obj.length; i++) {
                newObj[i] = deepClone(obj[i]);
            }
            return newObj;
        } else if (isJson) {
            // 克隆Object
            let newObj = {};
            //**Object.entries()**方法返回一个给定对象自身可枚举属性的键值对数组，不会遍历原型链上的
            for (let [key, value] of Object.entries(obj)) {
                newObj[key] = deepClone(value)
            }
            return newObj;
        }
        // 不是引用类型直接返回
        return obj;
    };

    Object.prototype.deepClone = function() {
        return deepClone(this);
    };
    Object.defineProperty(Object.prototype, 'deepClone', {enumerable: false});

    let object1 = {
        num:1,
        str:'string',
        nul:null,
        bool:true,
        regexp:new RegExp('test'),
        undef:undefined,
        arr:[1,'1','a',[1,'1','a'],{
            num:1,
            arr:[1,{
                num:1
            }]
        }],
        obj:{
            num:1,
            str:'string',
            arr:[1,'1','a',[1,'1','a'],{num:1,arr:[1]}]
        },
        fn:function(){
            console.log(1+2)
            return 'func1'
        }
    }

    let object2 = object1.deepClone()

    object2.num = 2
    object2.arr[0] = 2
    object2.arr[3][0] = 2
    object2.arr[4].num = 2
    object2.arr[4].arr[0] = 2
    object2.arr[4].arr[1].num = 2
    object2.obj.num = 2
    object2.obj.arr[0] = 2
    object2.obj.arr[3][0] = 2
    object2.obj.arr[4].num = 2
    object2.obj.arr[4].arr[0] = 2
    //object2.fn = function(){return "func2"}

    console.log(object1,object2)
    console.log(JSON.stringify(object1))
    console.log(JSON.stringify(object2))
    console.log(object1.fn(),object2.fn())
    console.log(object1.fn,object2.fn)

</script>
</html>